package com.example.play.vm

import android.util.Log
import com.blankj.utilcode.util.GsonUtils
import com.example.common.entity.CommendEntity
import com.example.common.entity.CommendReply
import com.example.common.vm.BaseViewModel
import com.example.play.entity.DanmuEntity
import com.example.play.intent.PlayViewIntent
import com.example.play.repo.PlayVideoRepository
import com.example.play.state.PlayUiState
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody

/**
 * 播放详情ViewModel
 */
@HiltViewModel
class PlayViewModel :BaseViewModel<PlayViewIntent>() {
    private val repository:PlayVideoRepository = PlayVideoRepository()

    private val _uiShareFlow = MutableSharedFlow<PlayUiState>()
    val uiSharedFlow: SharedFlow<PlayUiState> = _uiShareFlow.asSharedFlow()
    override fun dispatchIntent(intent: PlayViewIntent) {

        when(intent){
            is PlayViewIntent.LoadAuthorInfo -> getAuthorById(intent.userId)
            is PlayViewIntent.LoadRecommendSimpleVideo -> getRecommendSimpleVideo(intent.page, intent.pageSize)
            is PlayViewIntent.LoadSimpleVideoByChannelId -> getSimpleVideoByChannelId(intent.channelId, intent.page, intent.pageSize)
            is PlayViewIntent.LoadRecommendMultiVideo -> getRecommendMultiVideo(intent.page, intent.pageSize)
            is PlayViewIntent.LoadMultiVideoByTypeId -> getMultiVideoByTypeId(intent.typeId, intent.page, intent.pageSize)
            is PlayViewIntent.LoadVideoDanmuMsg -> getVideoDanmuMsg(intent.dataType, intent.itemId)
            is PlayViewIntent.PublishVideoComment -> publishComment(intent.content)
            is PlayViewIntent.PublishDanmuMsg -> publishDanmuMsg(intent.content)
            is PlayViewIntent.LoadCommentByUserId -> getCommentByUserId(intent.dataType, intent.itemId)
        }
    }


    /**
     * 获取视频作者信息
     */
    private fun getAuthorById(userId: String){
        mViewModelScope.launch(mDispatcher) {
            repository.getAuthorById(userId).collectLatest {
                if (it != null){
                    _uiShareFlow.emit(PlayUiState.LoadAuthorSuccess(it))
                } else {
                    _uiShareFlow.emit(PlayUiState.LoadAuthorFail("获取当前视频作者信息失败！！"))
                }
            }
        }
    }

    /**
     * 获取首页推荐视频
     */
    private fun getRecommendSimpleVideo(page: Int, pageSize: Int){
        mViewModelScope.launch(mDispatcher) {
            repository.getRecommendSimpleVideo(page, pageSize).collectLatest {
                if (it.isNotEmpty()){
                    _uiShareFlow.emit(PlayUiState.LoadSimpleVideoSuccess(it))
                } else {
                    _uiShareFlow.emit(PlayUiState.LoadSimpleVideoFail("获取当前视频失败！！"))
                }
            }
        }

    }

    /**
     * 获取首页分类下视频
     */
    private fun getSimpleVideoByChannelId(channelId: String,page: Int,pageSize: Int){
        mViewModelScope.launch(mDispatcher) {
            repository.getSimpleVideoByChannelId(channelId, page, pageSize).collectLatest {
                if (it.isNotEmpty()){
                    _uiShareFlow.emit(PlayUiState.LoadSimpleVideoSuccess(it))
                } else {
                    _uiShareFlow.emit(PlayUiState.LoadSimpleVideoFail("获取当前视频失败！！"))
                }
            }
        }
    }

    /**
     * 获取放映厅推荐视频
     */
    private fun getRecommendMultiVideo(page: Int,pageSize: Int){
        mViewModelScope.launch(mDispatcher) {
            repository.getRecommendMultiVideo(page, pageSize).collectLatest {
                if (it.isNotEmpty()){
                    _uiShareFlow.emit(PlayUiState.LoadMultiVideoSuccess(it))
                    Log.d("qqq123123", "getRecommendMultiVideo: $it")
                } else {
                    _uiShareFlow.emit(PlayUiState.LoadMultiVideoFail("获取当前放映厅视频失败！！"))
                }
            }
        }

    }

    /**
     * 获取放映厅分类下视频
     */
    private fun getMultiVideoByTypeId(typeId: Int, page: Int, pageSize: Int) {
        mViewModelScope.launch(mDispatcher) {
            repository.getMultiVideoByTypeId(typeId, page, pageSize).collectLatest {
                if (it.isNotEmpty()){
                    _uiShareFlow.emit(PlayUiState.LoadMultiVideoSuccess(it))
                    Log.d("qqq", "getMultiVideoByTypeId: $it")
                } else {
                    _uiShareFlow.emit(PlayUiState.LoadMultiVideoFail("获取当前放映厅视频失败！！"))
                }
            }
        }
    }

    /**
     * 获取视频评论
     */
    private fun getCommentByUserId(dataType: Int, itemId: String){
        mViewModelScope.launch(mDispatcher) {
            repository.getCommentByUserId(dataType, itemId).collectLatest {
                if (it.isNotEmpty()){
                    //处理数据
                    it.map { entity ->
                        randomConfigReplyComment(entity)
                    }
                    _uiShareFlow.emit(PlayUiState.LoadVideoCommentSuccess(it))
                } else {
                    _uiShareFlow.emit(PlayUiState.LoadVideoCommentFail("获取当前视频评论列表失败！！"))
                }
            }
        }

    }

    /**
     * 发送评论
     */
    private fun publishComment(str: String){
        mViewModelScope.launch(mDispatcher) {
            //创建评论对象
            var commendEntity = CommendEntity(
                content = str,
                datatype = 0,
            )

            //封装成RequestBody对象
            var body: RequestBody = GsonUtils.toJson(commendEntity).toRequestBody("application/json;charset=utf-8".toMediaTypeOrNull())

            //执行请求
            repository.publishComment(body).collectLatest {
                if (it != null){
                    _uiShareFlow.emit(PlayUiState.PublishVideoCommentSuccess(it))
                } else {
                    _uiShareFlow.emit(PlayUiState.PublishVideoCommentFail("发布视频评论失败！！"))
                }
            }
        }
    }

    /**
     * 发布弹幕
     */
    private fun publishDanmuMsg(danmu: String){
        mViewModelScope.launch(mDispatcher) {
            //创建评论对象
            var danmuEntity = DanmuEntity(
                content = danmu,
                datatype = 0,
            )

            //封装成RequestBody对象
            var body: RequestBody = GsonUtils.toJson(danmuEntity).toRequestBody("application/json;charset=utf-8".toMediaTypeOrNull())

            repository.publishDanmuMsg(body).collectLatest {
                if (it.isNotEmpty()){
                    _uiShareFlow.emit(PlayUiState.PublishVideoDanmuSuccess(it))
                } else {
                    _uiShareFlow.emit(PlayUiState.PublishVideoDanmuFail("发送视频弹幕失败！！"))
                }
            }
        }
    }

    /**
     * 获取视频弹幕
     */
    private fun getVideoDanmuMsg(dataType: Int, itemId: String) {
        mViewModelScope.launch(mDispatcher) {
            repository.getVideoDanmuMsg(dataType, itemId).collectLatest {
                if (it.isNotEmpty()){
                    _uiShareFlow.emit(PlayUiState.LoadVideoDanmuSuccess(it))
                } else {
                    _uiShareFlow.emit(PlayUiState.LoadVideoDanmuFail("获取当前视频弹幕失败！！"))
                }
            }
        }

    }


    /**
     * 模拟返回评论数据
     */
    private var mockReplyCommendList = listOf(
        CommendReply(0, 0, "我来了", "2023-12-20 14:23:21", 0, "小西", 0, 1, "https://p1-dy.bytexservice.com/img/user-avatar/d71e237251a88a91222c30a4dc3bf9e6~300x300.image" ),
        CommendReply(0, 0, "假的真不了", "2023-12-20 14:23:23", 1, "小西", 0, 1, "https://p1-dy.bytexservice.com/img/user-avatar/d71e237251a88a91222c30a4dc3bf9e6~300x300.image" ),
        CommendReply(0, 0, "言之有理", "2023-12-20 14:23:25", 2, "小西", 0, 1, "https://p1-dy.bytexservice.com/img/user-avatar/d71e237251a88a91222c30a4dc3bf9e6~300x300.image" ),
        CommendReply(0, 0, "我觉得太假了，一点儿不真实！！", "2023-12-20 14:23:26", 3, "小西", 0, 1, "https://p1-dy.bytexservice.com/img/user-avatar/d71e237251a88a91222c30a4dc3bf9e6~300x300.image" ),
        CommendReply(0, 0, "啥也不是！！", "2023-12-20 14:23:26", 4, "小西", 0, 1, "https://p1-dy.bytexservice.com/img/user-avatar/d71e237251a88a91222c30a4dc3bf9e6~300x300.image" ),
        CommendReply(0, 0, "太傻了！！", "2023-12-20 14:23:26", 5, "小西", 0, 1, "https://p1-dy.bytexservice.com/img/user-avatar/d71e237251a88a91222c30a4dc3bf9e6~300x300.image" ),
        CommendReply(0, 0, "我觉得太假了，一点儿不真实！！", "2023-12-20 14:23:26", 6, "小西", 0, 1, "https://p1-dy.bytexservice.com/img/user-avatar/d71e237251a88a91222c30a4dc3bf9e6~300x300.image" ),
        CommendReply(0, 0, "给你点赞！！", "2023-12-20 14:23:26", 7, "小西", 0, 1, "https://p1-dy.bytexservice.com/img/user-avatar/d71e237251a88a91222c30a4dc3bf9e6~300x300.image" ),
        CommendReply(0, 0, "努力加油！！", "2023-12-20 14:23:26", 8, "小西", 0, 1, "https://p1-dy.bytexservice.com/img/user-avatar/d71e237251a88a91222c30a4dc3bf9e6~300x300.image" ),
        CommendReply(0, 0, "我觉得太假了，一点儿不真实！！", "2023-12-20 14:23:26", 9, "小西", 0, 1, "https://p1-dy.bytexservice.com/img/user-avatar/d71e237251a88a91222c30a4dc3bf9e6~300x300.image" ),
        CommendReply(0, 0, "加油！！", "2023-12-20 14:23:26", 10, "小西", 0, 1, "https://p1-dy.bytexservice.com/img/user-avatar/d71e237251a88a91222c30a4dc3bf9e6~300x300.image" ),
        CommendReply(0, 0, "一点儿不真实！！", "2023-12-20 14:23:26", 11, "小西", 0, 1, "" ),
        CommendReply(0, 0, "牛逼牛逼，太漂亮了！！", "2023-12-20 14:23:26", 12, "小西", 0, 1, "https://p1-dy.bytexservice.com/img/user-avatar/d71e237251a88a91222c30a4dc3bf9e6~300x300.image" ),
    )


    private fun randomConfigReplyComment(entity: CommendEntity){
        entity.userlogo = "https://sf1-cdn-tos.bdxiguastatic.com/img/user-avatar/f4217ff67c16a8daf70e423cccc602fb~300x300.image"
        //随机取几条数据
        var randomNum = (Math.random() * 10 + 1).toInt()
        entity.replytotal = randomNum
        //设置二级评论
        while (randomNum > 0){
            var fromIndex = (mockReplyCommendList.size - 2) % ((Math.random() * 10).toInt() + 1)
            entity.replyList.addAll(mockReplyCommendList.subList(fromIndex, fromIndex + 1))
            randomNum -= 1
        }
    }

}